import axios from "axios";
import qs from 'qs'
import {Notification, Message} from 'element-ui'
import store from "../store";


const request = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: "/api",
    // 超时
    timeout: 10000,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
});

// request拦截器
request.interceptors.request.use(
    config => {
        if ((config.url.split("/").length >= 2 || config.url === 'connect') && store.getters.getToken !== null) {
            config.headers['u-token'] = store.getters.getToken
            if (config.params !== undefined) {
                config.params.token = store.getters.getToken
            }
            if (config.data !== undefined) {
                config.data.token = store.getters.getToken
            }
        } else if (store.getters.getConnectionId !== null) {
            if (config.params !== undefined) {
                config.params.connectionId = store.getters.getConnectionId
            }
            if (config.data !== undefined) {
                config.data.connectionId = store.getters.getConnectionId
            }
        }
        if (config.headers['Content-Type'] === 'application/json') {
            config.data = JSON.stringify(config.data);
        } else {
            config.data = qs.stringify(config.data);
        }
        return config;
    },
    error => {
        console.log('err' + error);
        return Promise.reject(error);
    }
);

// 响应拦截器
request.interceptors.response.use(response => {
        // return response.data;
        const code = response.data.code
        if (code !== 200) {
            Notification.error({
                title: response.data.msg
            })
            if (code === 410) {
                store.dispatch("DisConnect")
            }
            if (code === 403) {
                store.dispatch('SetToken', null)
                store.dispatch('SetUsername', null)
            }
            return Promise.reject('error')
        } else {
            return response.data
        }
    },
    error => {
        console.log('err' + error)
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
);

export default request;
